﻿#include "connectlinemidrect.h"
#include <QDebug>

ConnectLineMidRect::ConnectLineMidRect(QGraphicsItem* parent, QPointF* start, QPointF* end)
        : QGraphicsRectItem(parent), m_start(start), m_end(end), m_select(false)
{
    updatePosition();
    hide();
}

QPainterPath ConnectLineMidRect::shape() const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}

QRectF ConnectLineMidRect::boundingRect() const
{
    return QRectF(-5, -5, 10, 10); // 10x10 的矩形
}

void ConnectLineMidRect::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setPen(QPen(Qt::black, 1));
    painter->setBrush(m_select ? Qt::blue : Qt::red);
    painter->drawRect(boundingRect());
}

void ConnectLineMidRect::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (boundingRect().contains(event->pos()))
    {
        m_select = true;
        update();
        event->accept();
    }
    else
    {
        return;
    }
}

static void calculatePivot(QPointF* start, QPointF* end, QPointF delta)
{
    if(start->x() == end->x())
    {
        *start += QPointF(delta.x(), 0);
        *end += QPointF(delta.x(), 0);
    }
    else if(start->y() == end->y())
    {
        *start += QPointF(0, delta.y());
        *end += QPointF(0, delta.y());
    }
}

void ConnectLineMidRect::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_select)
    {
        QPointF delta = event->scenePos() - event->lastScenePos();
        calculatePivot(m_start, m_end, delta);
        updatePosition();
        event->accept();
    }
    else
    {
        event->ignore();
        return;
    }
}

void ConnectLineMidRect::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_select)
    {
        m_select = false;
        update();
        event->accept();
    } else {
        event->ignore();
        return;
    }
}

void ConnectLineMidRect::updatePosition()
{
    QPointF midPoint = QPointF((*m_start + *m_end) / 2);
    setPos(midPoint);
}

